<template>
  <div class="main">
    <div class="title">
      <h1 class="tit">
        {{ titTime + data.companyName + "运行分析报告" }}
      </h1>
      <div class="btn">
        <button @click="addPDF">生成PDF报告</button>
        <button @click="xiazai">下载报告</button>
      </div>
    </div>
    <div class="type">
      <div class="type1">企业:{{ data.companyName }}</div>
      <div class="type1">
        报告类型:{{ data.dateType == 1 ? "月报" : "年报" }}
      </div>
      <div class="type1">时间周期:{{ data.dateString }}</div>
    </div>
    <el-divider />
    <div class="bigbox">
      <div class="tit">尊敬的 {{ data.companyName }} 企业:</div>
      <div class="content">
        <div style="margin-bottom: 10px">
          企业能耗设备共计{{ data.deviceTotalCount }}台;{{
            data.dateType == 1 ? "本月" : "本年"
          }}<span v-html="sbwh"></span>;{{ data.dateType == 1 ? "本月" : "本年"
          }}<span v-html="sbjx"></span>;{{
            data.dateType == 1 ? "本月" : "本年"
          }}使用人员上报的设备异常信息<span style="color: red">{{
            data.exceptionMessageCount
          }}</span
          >个;{{ data.dateType == 1 ? "本月" : "本年" }}设备启停异常事件<span
            style="color: red"
            >{{
              data.startAndStopExceptionCount
                ? data.startAndStopExceptionCount
                : 0
            }}</span
          >个;结合对设备的用能监测，对设备运行检修情况进行了总结评估，生成了设备运行报告，详情如下:
        </div>
        <div class="sbyn">
          <div class="index">1、设备用能</div>
          <div class="echarts">
            <div class="left" v-loading="pipe1Loading">
              <div id="sbyn1" style="width: 100%; height: 100%"></div>
            </div>
            <div class="right" v-loading="pipe2Loading">
              <div id="sbyn2" style="width: 100%; height: 100%"></div>
            </div>
          </div>
        </div>
        <div class="sblyl">
          <div class="index">2、设备利用率</div>
          <div class="echarts">
            <div
              v-loading="barLoading"
              id="sblyl"
              style="width: 100%; height: 100%"
            ></div>
          </div>
        </div>
        <div class="yxsj">
          <div class="index">3、设备运行时间</div>
          <NtTable
            v-loading="tableLoading1"
            :tableData="tableData1"
            :height="'300px'"
            :tableConfig="tableConfig1"
          >
          </NtTable>
        </div>
        <div class="ycxx">
          <div class="index">4、设备异常信息</div>
          <NtTable
            v-loading="tableLoading2"
            :tableData="tableData2"
            :height="'300px'"
            :tableConfig="tableConfig2"
          >
          </NtTable>
        </div>
        <div class="wbqk">
          <div class="index">5、设备维保情况</div>
          <NtTable
            v-loading="tableLoading3"
            :tableData="tableData3"
            :height="'300px'"
            :tableConfig="tableConfig3"
          >
          </NtTable>
        </div>
        <div class="yxpj">
          <div class="index">6、运行平均</div>
          <div class="text">
            <div class="tit">1、设备能耗波动</div>
            <div class="content">
              {{ data.deviceDownsDetails }}
            </div>
          </div>
          <div class="text">
            <div class="tit">2、设备开工率及利用率</div>
            <div class="content">
              {{ now }}设备利用率低于50%的设备有{{
                data.utilizationLowCount
              }}台,占比{{ data.utilizationLowRate + "%"
              }}{{
                +data.utilizationLowRate > 50
                  ? ",设备利用率低于50%的设备较多，大部分设备未全部出力，可调整生产，提高设备利用率"
                  : ""
              }};设备开动率大于80%的设备有{{
                data.runningRateSurpassEightyCount
              }}台,占比{{
                data.runningRateSurpassEighty + "%"
              }},设备开动率小于50%的设备有{{
                data.runningRateBelowFiftyCount
              }}台,占比{{
                data.runningRateBelowFifty + "%"
              }},设备开动率在50%-80%间的设备有{{
                data.runningRateBetweenCount
              }}台,占比{{ data.runningRateBetween + "%"
              }}{{
                +data.runningRateBelowFifty > 50
                  ? "，设备开动率低于50%的设备较多，大部分设备运行时间较少，可调整生产，提高设备开动率。"
                  : ""
              }}
            </div>
          </div>
          <div class="text">
            <div class="tit">3、设备异常信息</div>
            <div class="content">
              {{
                data.exceptionMessageCount == 0
                  ? now + "设备异常信息较少，请继续保持对设备平时的运维保养"
                  : now + "设备异常信息数为" + data.exceptionMessageCount
              }}。
              {{
                data.startAndStopExceptionCount == 0
                  ? now + "无设备启停异常情况，请继续保持"
                  : now +
                    "设备启停异常事件数为" +
                    data.startAndStopExceptionCount
              }}。
            </div>
          </div>
          <div class="text">
            <div class="tit">4、设备节能潜力</div>
            <div class="content">
              {{ data.energySavingDetails }}
            </div>
          </div>
          <div class="text">
            <div class="tit">5、设备检修维保</div>
            <div class="content">
              {{
                data.maintenanceCount == 0
                  ? now + "没有需要保养的设备"
                  : now + "需要保养的设备数为" + data.maintenanceCount
              }}。
              {{
                data.repairCount == 0
                  ? now + "没有设备检修，生产过程中设备运行情况良好，请继续保持"
                  : now + "设备需检修数为" + data.repairCount
              }}。
            </div>
          </div>
        </div>
        <div class="yxjy">
          <div class="index">7、运行建议</div>
          <div class="content" style="font-weight: bold">
            1、注意设备利用率和设备运行时间，合理安排设备与生产关系，尽量保持设备在最佳工况下运行。<br />
            2、及时进行设备保养检修，提高设备效率和使用年限，保障正常生产。<br />
            3、对耗能较高的设备进行节能改造，利用目前能耗信息，进行投资收益测算，可按实际情况分批进行改造。<br />
            4、加大设备启停的管理，严禁设备在非生产时间启停，减少不必要的能源浪费。
          </div>
        </div>
        <div class="yxjy">
          <div class="index">8、说明</div>
          <div class="content">
            本报告得出的运行评价及提出的运行建议是根据对设备的监测数据分析所得，具体情况需要相关人员结合生产实际情况进行判断。
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import dayjs from 'dayjs'
import * as echarts from 'echarts'
import {
  getBarDataApi,
  getPipe1DataApi,
  getPipe2DataApi,
  getRunningAListApi,
  getExceptionListApi,
  getLedgerListApi,
  addPDFReportApi
} from '@/api/energy-consumption/Equipment-energy/Operation-analysis'
import NtTable from '@/components/nt-table'
import download from 'downloadjs'
import axios from 'axios'
export default {
  name: 'mReportIndex',
  props: ['data'],
  components: { NtTable },
  data () {
    return {
      pipe1Loading: false,
      pipe2Loading: false,
      barLoading: false,
      tableLoading1: false,
      tableLoading2: false,
      tableLoading3: false,
      pipe1List: [],
      pipe2List: [],
      barList: [],
      tableData1: [],
      tableData2: [],
      tableData3: [],
      tableConfig1: [
        {
          label: '序号',
          type: 'index',
          align: 'center',
          width: '100px'
        },
        {
          label: '时间段',
          prop: 'time',
          align: 'center'
        },
        {
          label: '设备名称',
          prop: 'className',
          align: 'center'
        },
        {
          label: '设备运行时间(h)',
          prop: 'runningTime',
          align: 'right',
          formatter: (row, column, cellValue, index) => {
            return Number(cellValue)?.toFixed(2)
          }
        },
        {
          label: '设备开动率(%)',
          prop: 'runningRate',
          align: 'right',
          formatter: (row, column, cellValue, index) => {
            return Number(cellValue)?.toFixed(2)
          }
        }
      ],
      tableConfig2: [
        {
          label: '序号',
          type: 'index',
          align: 'center',
          width: '100px'
        },
        {
          label: '用电企业',
          prop: 'companyName'
        },
        {
          label: '设备名称',
          prop: 'className',
          align: 'center'
        },
        {
          label: '发现时间',
          prop: 'discoverTime',
          align: 'center'
        },
        {
          label: '发现人',
          prop: 'discoverer',
          align: 'center'
        },
        {
          label: '异常信息描述',
          prop: 'exceptionMessage'
        },
        {
          label: '联系电话',
          prop: 'telephone',
          align: 'right'
        }
      ],
      tableConfig3: [
        {
          label: '序号',
          type: 'index',
          align: 'center',
          width: '100px'
        },
        {
          label: '设备名称',
          prop: 'className',
          align: 'center'
        },
        {
          label: '编号',
          prop: 'bh',
          align: 'center'
        },
        {
          label: '设备型号',
          prop: 'type',
          align: 'center'
        },
        {
          label: '生产厂家',
          prop: 'factory',
          align: 'center'
        },
        {
          label: '出场时间',
          prop: 'ccrq',
          align: 'center'
        },
        {
          label: '投运时间',
          prop: 'runDate',
          align: 'center'
        },
        {
          label: '维保时间(天)',
          prop: 'maintenance',
          align: 'center'
        },
        {
          label: '下次维保时间',
          prop: 'nextMaintenanceDate',
          align: 'center'
        }
      ]
    }
  },

  computed: {
    titTime () {
      return dayjs(this.data.dateString).format(
        this.data.dateType == 1 ? 'YYYY年M月' : 'YYYY年'
      )
    },
    sbwh () {
      if (this.data.maintenanceCount == 0) {
        return '<span style="color:red">【无】</span>需要保养的设备'
      } else {
        return `需要保养的设备为<span style="color:red">${this.data.maintenanceCount}</span>台`
      }
    },
    sbjx () {
      if (this.data.repairCount == 0) {
        return '<span style="color:red">【无】</span>需要设备进行检修'
      } else {
        return `需要设备进行检修<span style="color:red">${
          this.data.repairCount ? this.data.repairCount : 0
        }</span>台`
      }
    },
    now () {
      return this.data.dateType == 1 ? '本月' : '本年'
    }
  },
  mounted () {
    this.getdatalist()
  },
  methods: {

    // 下载
    xiazai () {
      axios({
        method: 'POST',
        url: `/biz/ecm-microservice-biz/ecm/device/operation/analysis/download/pdf?id=${this.data.id}`,
        responseType: 'blob'
      }).then(res => {
        const blob = new Blob([res.data], { type: 'application/pdf' })
        download(blob, '设备运行报告.pdf')
      })
    },
    // 生成PDF报告
    async addPDF () {
      console.log(this.data)
      const energyLastChart = this.createBase64('#sbyn2')
      const energyNowChart = this.createBase64('#sbyn1')
      const utilizationRateChart = this.createBase64('#sblyl')
      const res = await addPDFReportApi({
        energyLastChart,
        energyNowChart,
        utilizationRateChart,
        id: this.data.id
      })
      this.$message({
        type: res.code == 200 ? 'success' : 'error',
        message: res.code == 200 ? 'PDF报告生成成功' : res.message,
        duration: 2000
      })
    },
    // 获取数据
    async getdatalist () {
      const promises = [
        this.getPipe1Data().then(() => this.myChart1(this.pipe1List, 1)),
        this.getPipe2Data().then(() => this.myChart1(this.pipe2List, 2)),
        this.getBarData().then(() => this.myChart2(this.barList)),
        this.getRunningAList(),
        this.getExceptionList(),
        this.getLedgerList()
      ]

      // 等待所有Promise完成
      await Promise.all(promises)
    },
    async getPipe1Data () {
      this.pipe1Loading = true
      const res = await getPipe1DataApi({
        companyId: this.data.companyId,
        dateType: this.data.dateType,
        dateString: this.data.dateString
      })
      this.pipe1List = res.data.list
      this.pipe1Loading = false
    },
    async getPipe2Data () {
      this.pipe2Loading = true
      const res = await getPipe2DataApi({
        companyId: this.data.companyId,
        dateType: this.data.dateType,
        dateString: this.data.dateString
      })
      this.pipe2List = res.data.list
      this.pipe2Loading = false
    },
    // 设备利用率
    async getBarData () {
      this.barLoading = true
      const res = await getBarDataApi({
        companyId: this.data.companyId,
        dateType: this.data.dateType,
        dateString: this.data.dateString
      })
      this.barList = res.data.list
      this.barLoading = false
    },
    // 设备异常信息
    async getExceptionList () {
      this.tableLoading2 = true
      const res = await getExceptionListApi({
        companyId: this.data.companyId,
        dateType: this.data.dateType,
        dateString: this.data.dateString
      })
      this.tableData2 = res.data.list
      this.tableLoading2 = false
    },
    // 设备维保情况
    async getLedgerList () {
      this.tableLoading3 = true
      const res = await getLedgerListApi({
        companyId: this.data.companyId,
        dateType: this.data.dateType,
        dateString: this.data.dateString
      })
      this.tableData3 = res.data.list
      this.tableLoading3 = false
    },
    // 运行时间
    async getRunningAList () {
      this.tableLoading1 = true
      const res = await getRunningAListApi({
        companyId: this.data.companyId,
        dateType: this.data.dateType,
        dateString: this.data.dateString
      })
      this.tableData1 = res.data.list
      this.tableLoading1 = false
    },
    myChart1 (list, n) {
      const data1 =
        list.length > 0
          ? list.map((i) => {
            return {
              name:
                  i.deviceName +
                  ':' +
                  `${i.valueReading.toFixed(2)}kWh(${i.valueRate}%)`,
              value: i.valueRate
            }
          })
          : []
      const myChart1 = echarts.init(
        document.getElementById(n == 1 ? 'sbyn1' : 'sbyn2')
      )
      myChart1.setOption({
        legend: {
          type: 'scroll',
          bottom: 0,
          width: '90%',
          data: data1.map((i) => i.name),
          formatter: function (name) {
            return name.split(':')[0]
          }
        },
        series: [
          {
            type: 'pie',
            center: ['50%', '50%'],
            radius: ['40%', '55%'],
            avoidLabelOverlap: true,
            emphasis: {
              label: {
                show: true,
                fontSize: '20',
                fontWeight: 'bold'
              }
            },
            data: data1
          }
        ]
      })

      window.addEventListener('resize', () => {
        // 图表响应处理
        myChart1.resize()
      })
    },
    myChart2 (list) {
      const data = list.map((i) => {
        return [i.timeReading, i.valueReading]
      })
      const myChart = echarts.init(document.getElementById('sblyl'))
      myChart.setOption({
        // legend: {
        //   type: 'scroll',
        //   bottom: 0,
        //   data: data1.map((i) => i.name),
        //   formatter: function (name) {
        //     return name.split(':')[0]
        //   }
        // },
        xAxis: {
          type: 'category'
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            type: 'bar',
            label: {
              show: true,
              position: 'top',
              formatter: function (i) {
                return Number(i.value[1])?.toFixed(2) + '%'
              }
            },
            data: data,
            itemStyle: {
              borderRadius: [5, 5, 0, 0]
            }
          }
        ]
      })

      window.addEventListener('resize', () => {
        // 图表响应处理
        myChart.resize()
      })
    },
    createBase64 (ele) {
      const docEle = ele + ' canvas'
      const canvasFixed = document.querySelector(docEle)
      const // 获取图表元素
        canvasWidth = canvasFixed.width
      const // 获取图表元素宽度
        canvasHeigth = canvasFixed.heigth
      const // 获取图表元素高度
        canvas2D = canvasFixed.getContext('2d')
      canvas2D.drawImage(canvasFixed, canvasWidth, canvasHeigth)
      return canvasFixed.toDataURL()
    }
  }
}
</script>

<style lang="scss" scoped>
.main {
  .title {
    position: relative;
    text-align: center;
    margin-bottom: 50px;
    .btn {
      position: absolute;
      top: 50%;
      right: 0;
      transform: translateY(-50%);
      button {
        background-color: #007cee;
        color: #fff;
        border: none;
        padding: 5px;
        border-radius: 2px;
        margin-right: 10px;
      }
    }
  }
  .type {
    display: flex;
    align-items: center;
    height: 40px;
    .type1 {
      width: 200px;
      font-size: 20px;
    }
  }
  .bigbox {
    .content {
      padding: 0 40px;
      .sbyn {
        margin-bottom: 20px;
        .echarts {
          display: flex;
          height: 350px;
          .left {
            flex: 1;
          }
          .right {
            flex: 1;
          }
        }
      }
      .sblyl {
        margin-bottom: 20px;
        .echarts {
          height: 350px;
        }
      }
      .yxsj {
        margin-bottom: 50px;
        .index {
          margin-bottom: 50px;
        }
      }
      .ycxx {
        margin-bottom: 50px;
        .index {
          margin-bottom: 50px;
        }
      }
      .wbqk {
        margin-bottom: 50px;
        .index {
          margin-bottom: 50px;
        }
      }
      .yxpj {
        margin-bottom: 50px;
        .index {
          margin-bottom: 30px;
        }
        .text {
          .tit {
            font-weight: bold;
          }
        }
      }
      .yxjy {
        margin-bottom: 50px;
        .index {
          margin-bottom: 30px;
        }
      }
    }
  }
}
</style>
